package com.heima.comment.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.api.IArticleClient;
import com.heima.api.user.UserClient;
import com.heima.api.user.UserFegin;
import com.heima.api.wemedia.WemediaFeign;
import com.heima.comment.service.CommentService;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.model.article.dtos.ApArticleDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.comment.dtos.CommentDto;
import com.heima.model.comment.dtos.CommentLikeDto;
import com.heima.model.comment.dtos.CommentSaveDto;
import com.heima.model.comment.pojos.Comment;
import com.heima.model.comment.pojos.CommentReply;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
@Slf4j
public class CommentServiceImpl implements CommentService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IArticleClient iArticleClient;
    @Autowired
    private GreenTextScan greenTextScan;
    @Autowired
    private WemediaFeign wemediaFeign;
    @Autowired
    private UserFegin userFegin;

    @Override
    public ResponseResult saveComment(CommentSaveDto dto) {

        //自定义敏感词审核
        Boolean aBoolean = wemediaFeign.panduanSenistive(dto.getContent());
        if (!aBoolean) {
            log.info("文章中包含敏感词，不走后面的逻辑");
            return ResponseResult.errorResult(AppHttpCodeEnum.MINGANCI_EEOR);
        }
        //对文章进行垃圾检测，看是否有违规内容
        Boolean bollean = Scan(dto.getContent());
        if (!bollean) {
            log.info("文章中包含违规词，不走后面的逻辑");
            return ResponseResult.errorResult(AppHttpCodeEnum.MINGANCI_EEOR);
        }
        //判断文章内容不为空
        String content = dto.getContent();
        if (!StringUtils.hasText(content)) {
            log.info("评论内容不能为空");
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //文章字数审核
        if (!(content.length() <= 140)) {
            log.info("评论内容不能超过140个字");
            return ResponseResult.okResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Comment comment = new Comment();
        BeanUtils.copyProperties(dto, comment);
        comment.setEntryId(String.valueOf(dto.getArticleId()));
        //获取user相关信息
        ApUser user = AppThreadLocalUtil.getUser();
        comment.setAuthorId(user.getId());
        ResponseResult queryUser = userFegin.queryUser(user);
        String string = queryUser.getData().toString();
        ApUser apUser = JSON.parseObject(string, ApUser.class);
        comment.setImage(apUser.getImage());
        comment.setAuthorName(apUser.getName());
        comment.setCreatedTime(new Date());
        //通过文章id查询频道id ，获取文章相关信息
        ApArticle apArticle = new ApArticle();
        apArticle.setId(dto.getArticleId());
        ResponseResult result = iArticleClient.queryById(apArticle);
        String data = result.getData().toString();
        ApArticle data1 = JSON.parseObject(data, ApArticle.class);
        comment.setChannelId(data1.getChannelId());
        comment.setContent(dto.getContent());
        comment.setLikes(data1.getLikes());
        comment.setAddress(null);
        comment.setLongitude(null);
        comment.setLatitude(null);
        //新增评论数据到mogoDb中
        mongoTemplate.save(comment);
        //查询comment表中的评论数
        Criteria criteria = new Criteria();
        criteria.andOperator(Criteria.where("entryId").is(dto.getArticleId().toString()),
                Criteria.where("content").ne(null));
        List<Comment> commentReplies = mongoTemplate.find(Query.query(criteria), Comment.class);
        int comtentSize = commentReplies.size();
        //同步到article中
        ApArticle article = new ApArticle();
        for (Comment commentReply : commentReplies) {
            article.setId(Long.valueOf(commentReply.getEntryId()));
            article.setComment(comtentSize);
        }
        ApArticleDto articleDto = new ApArticleDto();
        BeanUtils.copyProperties(article, articleDto);
        iArticleClient.saveArticle(articleDto);
        return ResponseResult.okResult(comment);
    }

    /**
     * 对评论的文本内容进行审核
     *
     * @param content
     * @return
     */
    private Boolean Scan(String content) {
        try {
            Map map = greenTextScan.greeTextScan(content);
            if (map == null) {
                return true;
            }
            log.info("文本审核的结果{}", map);
            String type = map.get("suggestion") + "";
            if ("block".equals(type)) {
                //审核失败，修改状态为审核失败
                log.info("文本审核失败");
                return false;
            }
            if ("review".equals(type)) {
                log.info("文本审核异常");
                return false;
            }
            if ("pass".equals(type)) {
                log.info("文本审核成功");
                return true;
            }
        } catch (Exception e) {
            log.info("审核异常", e);
            return false;
        }
        return true;
    }

    @Override
    public ResponseResult queryList(CommentDto dto) {
        int page = 1;
        int pageSize = 10;
        Date date = dto.getMinDate();
        Criteria criteria = new Criteria();
        criteria.andOperator(Criteria.where("entryId").is(dto.getArticleId().toString()),
                Criteria.where("createdTime").lt(date));
        Query query = new Query(criteria);
        query.with(Sort.by(Sort.Direction.DESC, "createdTime"));
        query.skip((page - 1) * pageSize);
        query.limit(pageSize);
        List<Comment> comments = mongoTemplate.find(query, Comment.class);
        log.info("查询到的数据{}", comments);
        if (CollectionUtils.isEmpty(comments)) {
            log.info("没有评论");
        }
        return ResponseResult.okResult(comments);
    }

    @Override
    public ResponseResult addOrDeleteReply(CommentLikeDto dto) {
        log.info("前段传入的数据为{}",dto);
        CommentReply commentReply=new CommentReply();
        if(StringUtils.isEmpty(dto.getOperation()) || (dto.getOperation() != 0&&dto.getOperation()!=1)){
            log.info("数据没法用");
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        Criteria criteria=new Criteria();
        criteria.andOperator(Criteria.where("commentId").is(dto.getCommentId()),
                Criteria.where("content").ne(null));
        Query query=new Query();
        query.with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<CommentReply> comments = mongoTemplate.find(Query.query(criteria), CommentReply.class);
        if(!comments.isEmpty()){
            Long likes=0L;
            if(dto.getOperation()==1){
                likes=-1L;
            }else {
                likes=1L;
            }
            CommentReply comment = comments.get(0);
            log.info("这个的内容是{}",comment);
            commentReply.setId(UUID.randomUUID().toString());
            commentReply.setCommentId(comment.getId());
            if(comment.getLikes()==null||comment.getLikes()==0){
               comment.setLikes((long)0);
               commentReply.setOperation(null);

            }else {
                commentReply.setOperation((short)0);
            }
            log.info("这时候的点赞数位{}，，，，，，{}",comment.getLikes(),likes);
            commentReply.setLikes(comment.getLikes()==0&& likes<0? 0:Long.parseLong(comment.getLikes().toString())+likes);
            commentReply.setContent(null);
            commentReply.setUserId(AppThreadLocalUtil.getUser().getId());
            commentReply.setUserName("");
            commentReply.setCreateTime(new Date());
            mongoTemplate.save(commentReply);
            return ResponseResult.okResult(commentReply.getLikes().toString());
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
    }
}
